<?php
class Message extends CI_Model {
	var $id = 0;
	var $parent = null;
	var $user = null;
	var $content = "";
	var $replies = array();
	var $topics = array();
	var $posted = '';
	
	function __construct() {
		parent::__construct();
		$this->load->database();
	}
	
	function __construct($gid) {
		parent::__construct();
		$this->load->database();
		// Get message from database
		$query = $this->db->get_where('messages',array('message_id'=>$gid));
		if ($query->num_rows() > 0) {
			$this->id = $gid;
			$row = $query->row_array();
			$this->content = $row['content'];
			$this->timestamp = $row['posted'];
		} 
		else {
			return;
		}
		// Get relation to user
		$query = $this->db->get_where(
				'relations',
				array(
						'id2'=> $gid, 
						'type'=>'user-message',
				)
		);
		
		// Get relation to parent message(if any)
		$query = $this->db->get_where(
				'relations',
				array(
						'id2'=> $gid,
						'type'=>'reply-message',
				)
		);
		$row = $query->row_array();
		// Get relations to topics
		$query = $this->db->get_where(
				'relations',
				array(
						'id2'=> $gid,
						'type'=>'topic-message',
				)
		);
		foreach($query->result() as $row) {
			
		}
	}
	
	function fetch_by_id($gid) {
		$result = new Message($gid);
		return $result;		
	}
	
	function add_to_db() {
		// Add message to database
		// Add relation to user
		// Add relation to parent message(if any)
		// Add user action
		// Add relations to topics
	}
	
	function get_replies() {
		
	}
	
	function to_json() {
		$arr = array(
				'id' => $this->id,
				'content' => $this->content
		);
		return json_encode($arr);
	}
	
	function from_json($json) {
		$arr = json_decode($json);
		$this->id = $arr['id'];
		$this->content = $arr['content'];
	}
	
	
}